package com.ruoyi.web.controller.jiugongge;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.jiugongge.domain.Jiugongge;
import com.ruoyi.jiugongge.domain.JiugonggePrizes;
import com.ruoyi.jiugongge.domain.JiugonggeRecord;
import com.ruoyi.jiugongge.domain.JiugonggeRegistration;
import com.ruoyi.jiugongge.domain.WeixinDto;
import com.ruoyi.jiugongge.mapper.JiugonggePrizesMapper;
import com.ruoyi.jiugongge.mapper.JiugonggeRegistrationMapper;
import com.ruoyi.jiugongge.service.IJiugonggePrizesService;
import com.ruoyi.jiugongge.service.IJiugonggeRecordService;
import com.ruoyi.jiugongge.service.IJiugonggeService;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.common.utils.AjaxJson;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LotteryUtil;
import com.ruoyi.common.utils.RandomUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDUtil;
import com.ruoyi.common.utils.WeiXinHttpUtil;

/**
 * 九宫格活动 信息操作处理
 * 
 * @author lzy
 * @date 2019-01-14
 */
@Controller
@RequestMapping("/jiugongge")
public class JiugonggeIndexController extends BaseController {

	@Autowired
	private IJiugonggeService jiugonggeService;
	@Autowired
	private JiugonggePrizesMapper jiugonggePrizesDao;
	@Autowired
	IJiugonggePrizesService jiugonggePrizesService;
	@Autowired
	private JiugonggeRegistrationMapper jiugonggeRegistrationDao;
	@Autowired
	private IJiugonggeRecordService jiugonggeRecordService;

	protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(JiugonggeIndexController.class);


	/**
	 * @功能 跳转活动主页
	 * @时间 2019年2月20日
	 */
	@RequestMapping(value = "/toIndex", method = { RequestMethod.GET, RequestMethod.POST })
	public String toIndex(@ModelAttribute WeixinDto weixinDto, HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {
		logger.info("<-------跳转活动主页开始---------->");
		// 装载微信所需参数
		String jwid = weixinDto.getJwid();
		String appid = weixinDto.getAppid();
		String actId = weixinDto.getActId();
		String openid = weixinDto.getOpenid();
        String nickname = URLDecoder.decode(weixinDto.getNickname(), "UTF-8");
        weixinDto.setNickname(nickname);
		System.out.println("--------------------NICKNAME------------------"+nickname);
		

		 // 调试
		 /*weixinDto.setNickname("lzydemo"); 
		 String nickname = weixinDto.getNickname();
		 weixinDto.setHeadimgurl("https://micromart.oss-cn-beijing.aliyuncs.com/timg.jpg");
		 */

		Jiugongge wxActJiugongge = null;
		try {
			// 获取活动信息
			wxActJiugongge = jiugonggeService.selectJiugonggeById(actId);
			
			model.addAttribute("bargain", wxActJiugongge);
			
			if (wxActJiugongge == null) {
				model.addAttribute("errCode", false);
				model.addAttribute("errMsg", "活动不存在");
				return "jiugongge/error";
			}

			
			// 参数验证
			String validateWeixinDtoParam = validateWeixinDtoParam(weixinDto);

			if (validateWeixinDtoParam.equals("success") == false) {
				model.addAttribute("errCode", false);
				model.addAttribute("errMsg", validateWeixinDtoParam);
				return "jiugongge/error";
			}

			// 有效期内可参与
		   /*Date currDate = new Date();
			if (currDate.before(wxActJiugongge.getStarttime())) {

				String datePoor = DateUtils.getDatePoor(wxActJiugongge.getStarttime(), currDate);
				model.addAttribute("errCode", false);
				model.addAttribute("errMsg", wxActJiugongge.getTitle() + "活动倒计时" + datePoor + "请耐心等待！");
				return "jiugongge/error";

			}
			if (currDate.after(wxActJiugongge.getEndtime())) {
				model.addAttribute("errCode", false);
				model.addAttribute("errMsg", wxActJiugongge.getTitle() + "活动已结束!");
				return "jiugongge/error";

			}*/
			
			
			// 活动奖品
			List<JiugonggePrizes> wxActJiugonggePrizesList = jiugonggePrizesDao
					.selectJiugonggePrizesByActId(weixinDto.getActId());
			Map<String, String> prizeMap = new HashMap<String, String>();
			int i = 1;
			for (JiugonggePrizes wxActJiugonggePrizes : wxActJiugonggePrizesList) {
				prizeMap.put("prizeImg" + i, wxActJiugonggePrizes.getImg());
				i++;
			}
			model.addAttribute("prizeMap", prizeMap);
			model.addAttribute("prizeList", wxActJiugonggePrizesList);

			if (wxActJiugongge.getNumPerDay() == 0) {// 每天次数设置为0，代表不限制每天抽奖次数
				model.addAttribute("perday", 0);
			}
			// 根据访问人openid查询访问人的信息
			JiugonggeRegistration wxActJiugonggeRegistration = jiugonggeRegistrationDao
					.queryByOpenidAndActIdAndJwid(openid, actId, jwid);

			if (wxActJiugonggeRegistration == null) {
				// 判断当前活动参与人数是否已满
				// 判断参与人数是否超标
				int count = jiugonggeRecordService.getCountByActId(actId);
				int joinNumLimit = wxActJiugongge.getJoinNumLimit();
				if (joinNumLimit != 0) {
					if (count > (joinNumLimit - 1)) {
						model.addAttribute("errCode", false);
						model.addAttribute("errMsg","参与人数已满，请联系管理员");
						return "jiugongge/error";
					}
				}
				// for：判断当前活动参与人数是否已满
				wxActJiugonggeRegistration = new JiugonggeRegistration();
				wxActJiugonggeRegistration.setId(UUIDUtil.creatUUID());
				wxActJiugonggeRegistration.setActId(actId);
				wxActJiugonggeRegistration.setOpenid(openid);
				wxActJiugonggeRegistration.setNickname(nickname);
				wxActJiugonggeRegistration.setCreateTime(new Date());
				wxActJiugonggeRegistration.setAwardsStatus("0");
				wxActJiugonggeRegistration.setAwardsNum(0);
				wxActJiugonggeRegistration.setJwid(jwid);
				jiugonggeRegistrationDao.insertJiugonggeRegistration(wxActJiugonggeRegistration);// 如果当前访问人员不在参与活动的人员表中，则记录到参与活动人员表中
			}

			//if ("1".equals(wxActJiugongge.getFoucsUserCanJoin())) {// 如果活动设置了需要关注用户才能参加
				// velocityContext.put("qrcodeUrl",
				// baseApiJwidService.getQrcodeUrl(jwid));
			//}
			weixinDto.setNumberDay(jiugonggeRecordService.queryRecordListByOpenidAndActidAndJwid(weixinDto.getOpenid(),
					weixinDto.getActId(), weixinDto.getJwid(), DateUtils.getDate()).size());
			model.addAttribute("huodong_bottom_copyright", "lzy");
			model.addAttribute("registration", wxActJiugonggeRegistration);
			model.addAttribute("weixinDto", weixinDto);
			model.addAttribute("nonceStr", WeiXinHttpUtil.nonceStr);
			model.addAttribute("timestamp", WeiXinHttpUtil.timestamp);
			model.addAttribute("hdUrl", wxActJiugongge.getHdurl());
			model.addAttribute("appId", appid);
			model.addAttribute("signature", WeiXinHttpUtil.getRedisSignature(request, jwid));
		} catch (Exception e) {
			logger.info("<-------Exception---------->" + e.getMessage());
		}
		return "jiugongge/jiugongge";
	}

	private String validateWeixinDtoParam(WeixinDto weixinDto) {
		if (StringUtils.isEmpty(weixinDto.getActId())) {
			/*
			 * throw new
			 * JiugonggeException(JiugonggeExceptionEnum.ARGUMENT_ERROR,
			 * "活动ID不能为空");
			 */
			return "活动ID不能为空";
		}
		if (StringUtils.isEmpty(weixinDto.getOpenid())) {
			/*
			 * throw new
			 * JiugonggeException(JiugonggeExceptionEnum.ARGUMENT_ERROR,
			 * "参与人openid不能为空");
			 */
			return "参与人openid不能为空";
		}
		if (StringUtils.isEmpty(weixinDto.getJwid())) {
			/*
			 * throw new
			 * JiugonggeException(JiugonggeExceptionEnum.ARGUMENT_ERROR,
			 * "微信ID不能为空");
			 */
			return "微信ID不能为空";
		}
		return "success";
	}

	/**
	 * @功能 抽奖
	 * @时间 2019年2月23日
	 */
	@RequestMapping(value = "/getAwards", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public AjaxJson getAwards(@ModelAttribute WeixinDto weixinDto) {
		AjaxJson j = new AjaxJson();
		logger.info("----------活动抽奖开始-------------");
		// 装载微信所需参数
		String jwid = weixinDto.getJwid();
		String actId = weixinDto.getActId();
        String nickname = weixinDto.getNickname();
		try {

			// 参数验证
			String validateWeixinDtoParam = validateWeixinDtoParam(weixinDto);

			if (validateWeixinDtoParam.equals("success") == false) {
				j.setSuccess(false);
				j.setObj("验证微信参数错误");
				return j;
			}

			// 获取活动信息
			Jiugongge wxActJiugongge = jiugonggeService.selectJiugonggeById(weixinDto.getActId());

		/*	if ("1".equals(wxActJiugongge.getFoucsUserCanJoin())) {// 如果活动设置了需要关注用户才能参加
				// 未关注
				weixinDto.setSubscribe("0");
				// setWeixinDto(weixinDto);
				if (!"1".equals(weixinDto.getSubscribe())) {
					j.setSuccess(false);
					j.setObj("isNotFoucs");
					return j;
				}
			}*/
			// --update-end---author:huangqingquan---date:20161125-----for:是否关注可参加---------------

			/*
			 * if("1".equals(wxActJiugongge.getBindingMobileCanJoin())){//
			 * 如果活动设置了需要绑定手机号才能参加 // 获取绑定手机号 String bindPhone =
			 * getBindPhone(weixinDto.getOpenid(),jwid); // 判断是否绑定了手机号 if
			 * (StringUtils.isEmpty(bindPhone)) { j.setSuccess(false);
			 * j.setObj("isNotBind"); return j; } }
			 */
			
			
			// 判断总抽奖次数是否用完
			String currDate = DateUtils.getDate();
			List<JiugonggeRecord> bargainRecordList = jiugonggeRecordService.queryRecordListByOpenidAndActidAndJwid(
					weixinDto.getOpenid(), weixinDto.getActId(), weixinDto.getJwid());
			if (bargainRecordList != null && wxActJiugongge.getCount() != null && wxActJiugongge.getCount() != 0
					&& bargainRecordList.size() >= wxActJiugongge.getCount()) {
				j.setSuccess(false);
				j.setMsg("总抽奖次数已用完");
				return j;
			}
			
			// 判断今日抽奖次数是否用完
			if (wxActJiugongge.getNumPerDay() != 0) { // 每天次数设置为0，代表不限制每天抽奖次数，如果不等于0代表限制了每天抽奖次数
				bargainRecordList = jiugonggeRecordService.queryRecordListByOpenidAndActidAndJwid(weixinDto.getOpenid(),
						weixinDto.getActId(), weixinDto.getJwid(), currDate);
				if (bargainRecordList != null && bargainRecordList.size() >= wxActJiugongge.getNumPerDay()) {
					j.setSuccess(false);
					j.setMsg("今日抽奖次数已用完!");
					return j;
				}
			}
			// 生成用户的抽奖记录
			JiugonggeRecord wxActJiugonggeRecord = new JiugonggeRecord();
			wxActJiugonggeRecord.setId(RandomUtils.generateID());
			wxActJiugonggeRecord.setActId(weixinDto.getActId());
			logger.info("-------------------name---------------"+nickname);
			wxActJiugonggeRecord.setNickname(nickname);
			wxActJiugonggeRecord.setOpenid(weixinDto.getOpenid());
			wxActJiugonggeRecord.setJwid(weixinDto.getJwid());
			// update-begin--Author:zhangweijian Date: 20180413 for:修改抽奖时间,默认未中奖
			wxActJiugonggeRecord.setAwardTime(new Date());
			wxActJiugonggeRecord.setAwardStatus("0");
			// update-begin--Author:zhangweijian Date: 20180413 for:修改抽奖时间，默认未中奖
			Map<String, Object> map = new HashMap<String, Object>();
			// 为用户抽取活动奖品
			if ("0".equals(wxActJiugongge.getPrizeStatus())) {// 中奖可继续参与
				// 活动奖品
				List<JiugonggePrizes> awards = jiugonggePrizesService.queryRemainAwardsByActId(weixinDto.getActId());
				// 得到各奖品的概率列表
				List<Double> orignalRates = new ArrayList<Double>(awards.size());
				for (JiugonggePrizes award : awards) {
					Integer remainNum = award.getRemainNum();
					Double probability = award.getProbability();
					if (remainNum == null || remainNum <= 0) {// 剩余数量为零，需使它不能被抽到
						probability = new Double(0);
					}
					if (probability == null) {
						probability = new Double(0);
					}
					orignalRates.add(probability);
				}
				// 根据概率产生奖品
				JiugonggePrizes tuple = new JiugonggePrizes();
				int index = LotteryUtil.lottery(orignalRates);
				if (index >= 0) {// 中奖啦
					tuple = awards.get(index);
					wxActJiugonggeRecord.setAwardsId(tuple.getAwardId());
					// for:随机生成兑奖码，默认领奖状态为0
					wxActJiugonggeRecord.setAwardStatus("1");
					wxActJiugonggeRecord.setRecieveStatus("0");
					String awardCode = "";
					for (int i = 0; i < 4; i++) {
						awardCode = getCoupon();
						// 判断新生成的兑奖码是否存在
						JiugonggeRecord codeRecord = jiugonggeRecordService.queryByActIdAndawardCode(actId, awardCode);
						if (codeRecord == null) {
							break;
						}
						if (i == 3) {
							j.setSuccess(false);
							j.setMsg("参数异常");
							return j;
						}
					}
					wxActJiugonggeRecord.setAwardCode(awardCode);
					// for:随机生成兑奖码，默认领奖状态为0
					map.put("index", index + 1);
				}
			} else {// 一旦中奖不可继续参与
					// 中奖记录
				bargainRecordList = jiugonggeRecordService.queryMyAwardsByOpenidAndActidAndJwid(weixinDto.getOpenid(),
						weixinDto.getActId(), weixinDto.getJwid());
				if (bargainRecordList.size() == 0) {// 未曾中过奖项可继续正常参与抽奖
					// 活动奖品
					List<JiugonggePrizes> awards = jiugonggePrizesService
							.queryRemainAwardsByActId(weixinDto.getActId());
					// 得到各奖品的概率列表
					List<Double> orignalRates = new ArrayList<Double>(awards.size());
					for (JiugonggePrizes award : awards) {
						Integer remainNum = award.getRemainNum();
						Double probability = award.getProbability();
						if (remainNum == null || remainNum <= 0) {// 剩余数量为零，需使它不能被抽到
							probability = new Double(0);
						}
						if (probability == null) {
							probability = new Double(0);
						}
						orignalRates.add(probability);
					}
					// 根据概率产生奖品
					JiugonggePrizes tuple = new JiugonggePrizes();
					Integer index = LotteryUtil.lottery(orignalRates);
					if (index != null && index >= 0) {// 中奖啦
						tuple = awards.get(index);
						wxActJiugonggeRecord.setAwardsId(tuple.getAwardId());
						// for:随机生成兑奖码
						wxActJiugonggeRecord.setAwardStatus("1");
						wxActJiugonggeRecord.setRecieveStatus("0");
						String awardCode = "";
						for (int i = 0; i < 4; i++) {
							awardCode = getCoupon();
							// 判断新生成的兑奖码是否存在
							JiugonggeRecord codeRecord = jiugonggeRecordService.queryByActIdAndawardCode(actId,
									awardCode);
							if (codeRecord == null) {
								break;
							}
							if (i == 3) {
								j.setSuccess(false);
								j.setMsg("参数异常");
								return j;
							}
						}
						wxActJiugonggeRecord.setAwardCode(awardCode);
						// for:随机生成兑奖码
						map.put("index", index + 1);
					}
				}
			}

			JiugonggePrizes wxActJiugonggePrize = jiugonggeRecordService.creatAwards(wxActJiugonggeRecord);
			j.setSuccess(true);
			/*
			 * String basePath = request.getContextPath();
			 * map.put("basePath",basePath);
			 */
			map.put("wxActJiugonggeRecord", wxActJiugonggeRecord);
			map.put("wxActJiugonggePrize", wxActJiugonggePrize);
			j.setAttributes(map);

			j.setObj(wxActJiugonggePrize);
		} /*
			 * catch (JiugonggeException e) { e.printStackTrace();
			 * j.setSuccess(false); j.setMsg(e.getMessage()); logger.error(
			 * "bargain error:{}", e.getMessage()); }
			 */catch (Exception e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("很遗憾，您未中奖!");
			logger.error("bargain error:{}", e.getMessage());
		}
		return j;
	}

	/**
	 * 微信获取个人信息util
	 * 
	 * @param weixinDto
	 * @return 获取头像 Map两个键headimgurl,fxheadimgurl
	 */
	private Map<String, String> setWeixinDto(WeixinDto weixinDto) {
		logger.info("setWeixinDto parameter weixinDto={}", new Object[] { weixinDto });
		Map<String, String> map = new HashMap<String, String>();
		try {
			if (weixinDto.getOpenid() != null) {
				JSONObject jsonObj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getOpenid(), weixinDto.getJwid());
				logger.info("setWeixinDto Openid getGzUserInfo jsonObj={}", new Object[] { jsonObj });
				if (jsonObj != null && jsonObj.containsKey("subscribe")) {
					weixinDto.setSubscribe(jsonObj.getString("subscribe"));
				} else {
					weixinDto.setSubscribe("0");
				}
				if (jsonObj != null && jsonObj.containsKey("nickname")) {
					weixinDto.setNickname(jsonObj.getString("nickname"));
				} else {
					weixinDto.setNickname("");
				}
				if (jsonObj != null && jsonObj.containsKey("headimgurl")) {
					map.put("headimgurl", jsonObj.getString("headimgurl"));
				} else {
					map.put("fxheadimgurl", "");
				}
			}
			if (StringUtils.isNotEmpty(weixinDto.getFxOpenid())) {
				JSONObject jsonObj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getFxOpenid(), weixinDto.getJwid());
				logger.info("setWeixinDto FxOpenid getGzUserInfo jsonObj={}", new Object[] { jsonObj });
				if (jsonObj != null && jsonObj.containsKey("nickname")) {
					weixinDto.setFxNickname(jsonObj.getString("nickname"));
				} else {
					weixinDto.setFxNickname("");
				}
				if (jsonObj != null && jsonObj.containsKey("headimgurl")) {
					map.put("fxheadimgurl", jsonObj.getString("headimgurl"));
				} else {
					map.put("fxheadimgurl", "");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("setWeixinDto e={}", new Object[] { e });
		}
		return map;
	}

	/**
	 * @功能：随机生成兑奖码
	 * @return
	 */
	private synchronized static String getCoupon() {
		char ch[] = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
				'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
				'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z' };
		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 20; i++) {
			sb.append(ch[rand.nextInt(62)]);
		}
		return sb.toString();
	}

}
